import Vue from 'vue';
import Vuex from 'vuex';
import { getUserInfoAPI, getUserProfileAPI } from '../api/userAPI'

Vue.use(Vuex);

let initState = {
  tokenInfo: {},
  userInfo: {},
  userProfile: {}
};
const stateStr = localStorage.getItem('state');

if (stateStr) {
  initState = JSON.parse(stateStr);
}

export default new Vuex.Store({
  state: initState,
  mutations: {
    upDataTokenInfo(state, payload) {
      state.tokenInfo = payload;
      this.commit('saveStateToStorage');
    },
    saveStateToStorage(state) {
      localStorage.setItem('state', JSON.stringify(state));
    },
    updateUserInfo(state, payload) {
      state.userInfo = payload
      this.commit('saveStateToStorage')
    },
    cleanState(state) {
      state.tokenInfo = {}
      state.userInfo = {}
      state.userProfile = {}
      this.commit('saveStateToStorage')
    },
    updateUserProfile(state, payload) {
      state.userProfile = payload
      this.commit('saveStateToStorage')
    }
  },
  actions: {
    async initUserInfo(ctx) {
      const {data: res} = await getUserInfoAPI()
      if (res.message === 'OK') {
        // TODO：把数据转交给 Mutation 方法 ctx.commit('Mutation方法名')
        ctx.commit('updateUserInfo', res.data)
      }
    },
    async initUserProfile(ctx) {
      const {data: res} = await getUserProfileAPI()
      if (res.message === 'OK'){
        ctx.commit('updateUserProfile',res.data)
      }
    }
  },
  modules: {
  },
});
